from flask import request, redirect, jsonify, Blueprint, session
import requests
from config import db
from models.models import User
from utils.utils import get_now_data_time, md5

CLIENT_ID = 'c3695dcf852f3ec8d4d1089e50f4c846cd6a6d872013a6e6b9e797598da43760'
CLIENT_SECRET = 'f42e6e47b15836d26b01e988674bcdd3fc7fda9dbf709c402732c88e6a5bcf90'
REDIRECT_URI = 'http://localhost:5000/auth'
AUTHORIZE_URL = 'https://gitee.com/oauth/authorize'
ACCESS_TOKEN_URL = 'https://gitee.com/oauth/token'
USER_INFO_URL = 'https://gitee.com/api/v5/user'

gitee_login_service = Blueprint('gitee_login_service', __name__)


@gitee_login_service.route('/gitee/login')
def login():
    auth_url = f'{AUTHORIZE_URL}?client_id={CLIENT_ID}&redirect_uri={REDIRECT_URI}&response_type=code'
    return redirect(auth_url)


@gitee_login_service.route('/auth')
def callback():
    code = request.args.get('code')
    payload = {
        'client_id': CLIENT_ID,
        'client_secret': CLIENT_SECRET,
        'code': code,
        'grant_type': 'authorization_code',
        'redirect_uri': REDIRECT_URI,
    }
    response = requests.post(ACCESS_TOKEN_URL, data=payload)
    access_token = response.json().get('access_token')

    user_response = requests.get(USER_INFO_URL, headers={'Authorization': f'Bearer {access_token}'})
    user_info = user_response.json()
    gitee_user = {
        "id": user_info["id"],
        "username": user_info["login"],
        "name": user_info["name"]
    }
    session["user_id"] = gitee_user["id"]
    user = User.query.filter_by(id=gitee_user["id"]).first()
    data = []
    if user is not None and user.id == gitee_user["id"]:
        return redirect('/')
    else:
        password = md5(user_info["login"], '123456')
        new_user = User(
            id=user_info["id"],
            username=user_info["login"],
            password=password,
            name=user_info["name"],
            loginTime=get_now_data_time(),
            createTime=get_now_data_time(),
            role='git_user'
        )
        db.session.add(new_user)
        db.session.commit()
        return redirect('/')
